/*
 * Search for a non-superuser
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <pwd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>

#include "user.h"
#include "types.h"


int
user_get_regular(struct passwd *const pwd, const ErrorFn errh)
{
    assert(pwd != NULL);

    (void) memset(pwd, 0, sizeof(*pwd));

    int fatalerr = 0;
    int retval = 1;

    errno = 0;
    setpwent();
    /* cppcheck-suppress misra-c2012-22.10; setpwent sets errno */
    if (errno != 0) {
        if (errh != NULL) {
            errh(EXIT_FAILURE, "setpwent");
        }
        return -1;
    }

    const struct passwd *ptr;
    /* cppcheck-suppress getpwentCalled; getpwent_r is not portable */
    while ((errno = 0, ptr = getpwent()) != NULL) {
        if (ptr->pw_uid > 0) {
            /* RATS: ignore; can neither over- nor underflow */
            (void) memcpy(pwd, ptr, sizeof(*ptr));
            retval = 0;
            break;
        }
    }

    /* cppcheck-suppress misra-c2012-22.10; getpwent sets errno */
    if (ptr == NULL && errno != 0) {
        fatalerr = errno;
        retval = -1;
    }

    errno = 0;
    endpwent();
    /* cppcheck-suppress misra-c2012-22.10; endpwent sets errno */
    if (errno != 0) {
        if (retval != -1) {
            if (errh != NULL) {
                errh(EXIT_FAILURE, "endpwent");
            }
            retval = -1;
        } else {
            /* RATS: ignore; format string is short and a literal */
            syslog(LOG_ERR, "endpwent");
        }
    }

    errno = fatalerr;
    if (retval == -1 && errh != NULL) {
        errh(EXIT_FAILURE, "getpwent");
    }

    return retval;
}
